package middleware

import (
	"github.com/go-kratos/kratos/v2/log"
	"github.com/go-kratos/kratos/v2/transport/http"
	"google.golang.org/grpc/status"
	netHttp "net/http"
)

// HttpErrorResponse http 错误响应封装
type HttpErrorResponse struct {
	Success   bool   `json:"success"`
	Error     string `json:"error"`
	ErrorCode string `json:"errorCode"`
}

// EncoderError 错误响应封装
func EncoderError(_ log.Logger) http.EncodeErrorFunc {
	return func(w http.ResponseWriter, r *http.Request, err error) {
		if err == nil {
			return
		}
		se := &HttpErrorResponse{Success: false, ErrorCode: "500"}
		gs, ok := status.FromError(err)
		if !ok {
			log.Errorf("error: %+v", err) // 解析不了 error
			w.WriteHeader(netHttp.StatusInternalServerError)

			return
		}
		se.Error = gs.Message()
		codec, _ := http.CodecForRequest(r, "Accept")
		body, err := codec.Marshal(se)
		if err != nil {
			log.Errorf("error: %+v", err) // 解析不了 http accept
			w.WriteHeader(netHttp.StatusInternalServerError)
			return
		}
		w.Header().Set("Content-Type", "application/"+codec.Name())
		w.WriteHeader(netHttp.StatusOK)
		_, _ = w.Write(body)
	}
}
